package com.ruoyi.hbase.controller;

import com.ruoyi.hbase.config.HbaseTemplate;
import com.ruoyi.hbase.dto.PeopleDto;
import com.ruoyi.hbase.dto.SaveTable;
import com.ruoyi.hbase.service.PeopleService;
import com.ruoyi.hbase.utils.Result;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("people")
public class PeopleController {

    @Autowired
    PeopleService peopleService;

    @Autowired
    private HbaseTemplate hbaseTemplate;

    @GetMapping("query/{startRow}/{stopRow}")
    public List<PeopleDto> query(@PathVariable String startRow, @PathVariable String stopRow) {
        return peopleService.query(startRow,stopRow);
        //return null;
    }

    //创建表
    @PostMapping("createTable")
    public Result createTable(@RequestParam("tableName") String tableName ,@RequestBody List<String> columnFamily){

        boolean flag = hbaseTemplate.createTable(tableName, columnFamily);
        if (flag){
            return Result.success("创建成功");
        }

       return Result.error("表已存在");
    }

    //查询库中所有表的表名
    @GetMapping("getAllTableNames")
    public Result getAllTableNames() {
        List<String> allTableNames = hbaseTemplate.getAllTableNames();
        if (allTableNames.isEmpty()){
            return Result.error("没有数据表");
        }

        return Result.success("查询成功",allTableNames);
    }


    //删除表
    @PostMapping("deleteTable")
    public Result deleteTable(@RequestParam("tableName") String tableName){

        boolean flag = hbaseTemplate.deleteTable(tableName);
        if (flag){
            return Result.success("删除成功");
        }

        return Result.error("删除失败");
    }
    //查询指定表中的数据
    @PostMapping("getResultScanner")
    public Result getResultScanner(@RequestParam("tableName") String tableName){
        Map<String, Map<String, String>> resultScanner = hbaseTemplate.getResultScanner(tableName);
        if (resultScanner.isEmpty()){
            return Result.error("没有数据");
        }

        return Result.success("查询成功",resultScanner);
    }

    //查询指定表中的数据
    @RequestMapping("putData")
    public Result putData(@RequestBody SaveTable saveTable){

        hbaseTemplate.putData(saveTable.getTableName(),saveTable.getRowKey(),saveTable.getFamilyName(),saveTable.getColumns(),saveTable.getValues());

        return Result.success("添加成功");
    }

}
